import { ReactElement } from 'react'
import moment, { Moment } from 'moment'
import style from './index.module.less'

interface Props {
  value?: string | Moment | number | object | Array<string | Moment | number | object>
  format?: string
  unit?: string
  empty?: string
  formatFn?: (v: any) => any
}

function Main ({ value, format = 'YYYY-MM-DD', unit, empty = '无', formatFn }: Props): ReactElement {
  if (value instanceof Array) {
    if (value.length === 0) {
      return <div className={style.container}>{empty}</div>
    }
    return (
      <div className={style.container}>
        {
          value.map((li, i: number) => {
            if (typeof formatFn === 'function') {
              return (
                <span key={i}>
                  <span>{i + 1}）</span>
                  <span>{formatFn(li)}</span>
                  <br/>
                </span>
              )
            }
            const v = li instanceof moment ? (li as Moment).format(format) : li
            return (
              <span key={i}>
                <span>{i + 1}）</span>
                <span>{(v === undefined || v === null) ? empty : v as any}</span>
                <span>{(typeof unit === 'string' && v !== undefined && v !== null) && unit}</span>
                <br/>
              </span>
            )
          })
        }
      </div>
    )
  }
  const v = value instanceof moment ? (value as Moment).format(format) : value
  return (
    <div className={style.container}>
      {v === undefined || v === null ? empty : v as any}
      {(typeof unit === 'string' && v !== undefined && v !== null) && unit}
    </div>
  )
}

export default Main
